package com.example.saifly.inPagePlan;

import android.annotation.SuppressLint;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseItemDraggableAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.common.Activity;
import com.example.common.Application.MyApplication;
import com.example.common.Retrofit.RetrofitHelper;
import com.example.saifly.Model.DailyPlanBg;
import com.example.saifly.Model.DailyPlanFinish;
import com.example.saifly.Model.DailyPlans;
import com.example.saifly.R;
import com.wang.avi.AVLoadingIndicatorView;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lecho.lib.hellocharts.view.LineChartView;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;

import static com.example.common.Util.TimeUtil.Date2StringHM;


@SuppressLint("Registered")
public class TodoActivity extends Activity {
    RecyclerView rvTodo;
    List<DailyPlans> dailyPlansList;              //前端保存的每日计划list
    List<DailyPlanBg> dailyPlanBgList;          //后端发送过来的每日计划list
    List<DailyPlanFinish> dailyPlanFinishList;  //后端发送过来的每日计划完成情况List
    Map<String, Integer> statusAndColor = new HashMap<String, Integer>();        //完成状态和背景颜色绑定
    Map<Integer, String> finishToString = new HashMap<Integer, String>();        //Integer描述完成与否和文字描述绑定
    Map<String, Integer> stringToFinish = new HashMap<String, Integer>();        //完成与否文字描述和Integer的反向转化
    MyAdapter myAdapter;

    //loading
    private RelativeLayout loadingLayout;
    private LineChartView lineChart;
    private AVLoadingIndicatorView loadingView;

    private ImageView ivReturn;     //返回图标
    private Button btStatus;        //记录是否完成
    private TextView tvPlanTime;    //计划执行时间
    private String patientPhone;
    private Boolean patientOrFamily;

    SharedPreferences sp = MyApplication.getContext().getSharedPreferences("config", Context.MODE_PRIVATE);;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        new Thread(new Runnable() {
            @Override
            public void run() {
                if(patientOrFamily == true){
                    SendPlanFinish();
                }
            }
        }).start();
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_plan_todo;
    }

    @Override
    protected void init() {
        super.init();
        initList();
        InitData();
        new Thread(new Runnable() {
            @Override
            public void run() {
                //如果是家属就展示其对应患者的每日计划
                GetDailyPlan(sp.getString("uid","110"),new Date().getTime());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        myAdapter.notifyDataSetChanged();
                    }
                });
            }
        }).start();
        if(sp.getString("identity", "patient").equals("patient")){
            patientOrFamily = true;
        }
        else {
            patientOrFamily = false;
        }
        //初始化


        rvTodo= findViewById(R.id.todo_rv);
        RecyclerView.LayoutManager layoutManager=new StaggeredGridLayoutManager(1,StaggeredGridLayoutManager.VERTICAL);
        rvTodo.setLayoutManager(layoutManager);

        myAdapter=new MyAdapter(dailyPlansList);
        rvTodo.setAdapter(myAdapter);

        ivReturn = findViewById(R.id.todo_return);
        tvPlanTime = findViewById(R.id.holder_plan_todo_content_time);
        btStatus = findViewById(R.id.holder_plan_todo_bt_status);
        loadingLayout = findViewById(R.id.todo_loading_layout);
        loadingView = findViewById(R.id.todo_loading_view);

        patientPhone = sp.getString("uid","110");
        doJump();
    }

    private void InitData() {
        statusAndColor.put("未完成",R.drawable.button_plan_unfinished);
        statusAndColor.put("已完成",R.drawable.button_plan_finish);
        finishToString.put(0,"未完成");
        finishToString.put(1,"已完成");
        stringToFinish.put("未完成",0);
        stringToFinish.put("已完成",1);
    }

    private void initList() {
        dailyPlansList = new ArrayList<>();
        dailyPlanBgList = new ArrayList<>();
        dailyPlanFinishList = new ArrayList<>();
    }

    //设置页面跳转逻辑
    private void doJump(){
        ivReturn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    // strTime要转换的string类型的时间，formatType要转换的格式yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日
    // HH时mm分ss秒，
    // strTime的时间格式必须要与formatType的时间格式相同
    public static Date stringToDate(String strTime, String formatType)  throws ParseException
    {
        SimpleDateFormat formatter = new SimpleDateFormat(formatType);
        Date date = null;
        date = formatter.parse(strTime);
        return date;
    }

    private void loadingStart(){
        loadingLayout.setOnClickListener(null);
        loadingLayout.setVisibility(View.VISIBLE);
        loadingView.show();
    }

    private void loadingEnd(){
        loadingView.hide();
        loadingLayout.setVisibility(View.GONE);
    }

    private class MyAdapter extends BaseItemDraggableAdapter<DailyPlans,BaseViewHolder>{

        public MyAdapter(List<DailyPlans> itemList) {
            super(R.layout.holder_plan_todo,dailyPlansList);
        }

        @Override
        protected void convert(@NonNull BaseViewHolder holder, DailyPlans item) {
            final int position=holder.getLayoutPosition();

            holder.setText(R.id.holder_plan_todo_content_title,dailyPlansList.get(position).getContent_title());
            holder.setText(R.id.holder_plan_todo_content_time,dailyPlansList.get(position).getContent_time());
            holder.setText(R.id.holder_plan_todo_bt_status,dailyPlansList.get(position).getStatus());
            holder.setBackgroundRes(R.id.holder_plan_todo_bt_status,dailyPlansList.get(position).getStatus_color());

            holder.addOnClickListener(R.id.todo_rv);
            holder.addOnClickListener(R.id.holder_plan_todo_content_time);
            holder.addOnClickListener(R.id.holder_plan_todo_bt_status);

            //如果是患者
            if(patientOrFamily == true){
                setOnItemChildClickListener(new OnItemChildClickListener() {
                    @Override
                    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position){
                        switch (view.getId())
                        {
                            case R.id.holder_plan_todo_content_time:
                                Calendar nowCal =  Calendar. getInstance();
                                new TimePickerDialog(TodoActivity.this, new TimePickerDialog.OnTimeSetListener() {
                                    @Override
                                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                        String temp = "使用时间 : ";
                                        temp += hourOfDay<10 ? "0"+hourOfDay : hourOfDay;
                                        temp += ":";
                                        temp += minute < 10 ? "0"+minute : minute;
                                        dailyPlansList.get(position).setContent_time(temp);
                                        Collections.sort(dailyPlansList);
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                myAdapter.notifyDataSetChanged();
                                            }
                                        });
                                        new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                SendPlanFinish();
                                            }
                                        }).start();
                                    }
                                },
                                        nowCal . get( Calendar . HOUR_OF_DAY ),
                                        nowCal . get( Calendar . MINUTE ),
                                        false
                                ).show();
                                break;
                            case R.id.holder_plan_todo_bt_status:
                                String nowTime = Date2StringHM(new Date());
                                String selectTime = dailyPlansList.get(position).getContent_time().replace("使用时间 : ","");
                                Log.d("123", "onItemChildClick: "+dailyPlansList.get(position).getStatus());
                                if(dailyPlansList.get(position).getStatus().equals("未完成")){
                                    if(nowTime.compareTo(selectTime) < 0){
                                        Toast.makeText(TodoActivity.this, "时间未到，无法完成，请稍后再试。", Toast.LENGTH_SHORT).show();
                                    }
                                    else{
                                        dailyPlansList.get(position).setStatus("已完成");
                                        dailyPlansList.get(position).setStatus_color(R.drawable.button_plan_finish);
                                        notifyDataSetChanged();
                                    }
                                }
                                else{
                                    dailyPlansList.get(position).setStatus("未完成");
                                    dailyPlansList.get(position).setStatus_color(R.drawable.button_plan_unfinished);
                                    notifyDataSetChanged();
                                }
                                break;
                            default:
                                break;
                        }
                    }
                });
            }
        }
    }

    //从后端获取今日计划
    private interface ApiGetDailyPlan{
        @Headers({"Content-Type:application/json"})                             //大家都不变
        @POST("/arrange/getDailyPlan")                                          //后端给的路径
        Call<ResponseBody> GetDailyPlan(@Body JSONObject jsonObject);
    }

    private void GetDailyPlan(String patientPhone,Long date){
        JSONObject jsonObject = new JSONObject();

        RetrofitHelper retrofitHelper=new RetrofitHelper();     //大家都一样
        Retrofit retrofit=retrofitHelper.getRetrofit();

        ApiGetDailyPlan apiGetDailyPlan = retrofit.create(ApiGetDailyPlan.class);
        jsonObject.put("patientPhone",patientPhone);
        jsonObject.put("date",date);

        Call<ResponseBody> call = apiGetDailyPlan.GetDailyPlan(jsonObject);
        final Response<ResponseBody> response;
        try{
            response = call.execute();
            if(response.body() != null){
                JSONObject resultJson=JSON.parseObject(response.body().string());
                if(resultJson.getInteger("code")!=null&&resultJson.getInteger("code")==1){
                    //这里放正常流程操作
                    String result  = resultJson.get("result").toString();
                    String resultDP = JSON.parseObject(result).get("dailyPlans").toString();
                    String resultDPF = JSON.parseObject(result).get("dailyPlanFinishes").toString();
                    Log.d("12345", "result: "+result);
                    Log.d("12345", "resultDP: "+resultDP);
                    Log.d("12345", "resultDPF: "+resultDPF);
                    dailyPlanBgList = JSONObject.parseArray(resultDP,DailyPlanBg.class);
                    dailyPlanFinishList = JSONObject.parseArray(resultDPF,DailyPlanFinish.class);

                    dailyPlansList.clear();
                    for(int i = 0; i < dailyPlanBgList.size(); i++){
                        dailyPlansList.add(new DailyPlans(dailyPlanBgList.get(i).getContent(),"使用时间 : "+Date2StringHM(dailyPlanBgList.get(i).getTime()),dailyPlanBgList.get(i).getPlanId()));
                    }
                    for(int i = 0; i < dailyPlanFinishList.size(); i++){
                        for(int j = 0; j < dailyPlansList.size(); j++){
                            //判断PlanId相等后，利用finishToString得到完成情况，再根据完成情况设置颜色背景
                            if(dailyPlansList.get(j).getPlanId().equals(dailyPlanFinishList.get(i).getPlanId())){
                                dailyPlansList.get(j).setStatus(finishToString.get(dailyPlanFinishList.get(i).getFinish()));
                                dailyPlansList.get(j).setStatus_color(statusAndColor.get(dailyPlansList.get(j).getStatus()));
                                break;
                            }
                        }
                    }
                    Collections.sort(dailyPlansList);
//            Log.d("12345", "dailyPlanList.size(): "+dailyPlanList.size());
                }
                else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(TodoActivity.this, "网络出现异常", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

            }
        } catch (IOException e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(TodoActivity.this, "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }
    }

    //给后端发送今日计划完成情况
    private interface ApiSendPlanFinish{
        @Headers({"Content-Type:application/json"})                             //大家都不变
        @POST("/plan/submitDailyPlanFinish")                                          //后端给的路径
        Call<ResponseBody> SendPlanFinish(@Body JSONObject jsonObject);
    }

    private void SendPlanFinish(){
        JSONObject jsonObject = new JSONObject();

        //将前台今日计划完成情况类转化为后台完成情况类
        //将今日计划的时间传给后台
        dailyPlanFinishList.clear();
        Date date = new Date();
        dailyPlanBgList.clear();
        for(int i = 0; i < dailyPlansList.size(); i++){
            DailyPlanFinish dailyPlanFinish = new DailyPlanFinish(date,dailyPlansList.get(i).getPlanId(),stringToFinish.get(dailyPlansList.get(i).getStatus()));
            dailyPlanFinishList.add(dailyPlanFinish);
            DailyPlanBg dailyPlanBg = null;
            try {
                dailyPlanBg = new DailyPlanBg(dailyPlansList.get(i).getPlanId(),dailyPlansList.get(i).getContent_title(),stringToDate(dailyPlansList.get(i).getContent_time().replace("使用时间 : ",""),"HH:mm"),patientPhone);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            dailyPlanBgList.add(dailyPlanBg);
        }


        String sendFinishInfo = JSON.toJSONString(dailyPlanFinishList);
        jsonObject.put("dailyPlanFinish",sendFinishInfo);
        String sendPlanInfo = JSON.toJSONString(dailyPlanBgList);
        jsonObject.put("dailyPlan",sendPlanInfo);
//        Log.d("123", "sendFinishInfo: "+sendFinishInfo);
//        Log.d("123", "sendPlanInfo: "+sendPlanInfo);
//        Log.d("123", "SendPlanFinish: "+jsonObject);

        RetrofitHelper retrofitHelper=new RetrofitHelper();     //大家都一样
        Retrofit retrofit=retrofitHelper.getRetrofit();

        ApiSendPlanFinish apiSendPlanFinish = retrofit.create(ApiSendPlanFinish.class);

        Call<ResponseBody> call = apiSendPlanFinish.SendPlanFinish(jsonObject);
        final Response<ResponseBody> response;
        try {

            response = call.execute();

            if(response.body() != null){
                JSONObject result=JSON.parseObject(response.body().string());
                if(result.getInteger("code")!=null&&result.getInteger("code")==1){
                    //这里放正常流程操作
                }
                else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(TodoActivity.this, "网络出现异常", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        } catch (IOException e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(TodoActivity.this, "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }
    }
}
